﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using Common.Extensions.OrderBy;
using Common.Extensions.Where;
using DomainModel;
using EmitMapper;
using IManager;
using Webdiyer.WebControls.Mvc;
using WebHelper.SessionHandler;
using WebPlatform.Areas.CPP.Models;
using WebPlatform.FiltersAndSession;

namespace WebPlatform.Areas.CPP.Controllers
{
    public class DefaultController : Controller
    {


        /// <summary>
        /// 产品业务
        /// </summary>
        public IManagerProduct IMProduct { get; set; }


        /// <summary>
        /// 用户信息操作
        /// </summary>
        public IManagerUser IMUser { get; set; }


        /// <summary>
        /// 会话操作
        /// </summary>
        public ISessionHandler ISHandler { get; set; }


        /// <summary>
        /// 企业信息
        /// </summary>
        public IManagerCompany IMCompany { get; set; }


        /// <summary>
        /// 登录会话操作
        /// </summary>
        public Sessions Sessions { get; set; }


        /// <summary>
        /// 文章
        /// </summary>
        public IManagerContent IMContent { get; set; }


        public IManagerArticle IMArticle { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public IManagerLinks IMLinks { get; set; }



        public ActionResult Index()
        {

            BindArticle();
            return View();
        }


        void BindArticle()
        {

            ViewBag.HAD = GetArticles("HAD");

            ViewBag.HF = IMLinks.GetLink(1, "HT");


            ViewBag.HSDT = GetArticles("HSDT");


            var company = IMCompany.GetCompany(1);
            ViewBag.Media = company;
        }






        /// <summary>
        /// 读取文章
        /// </summary>
        /// <param name="partitionId"></param>
        /// <returns></returns>
        IList<ArticleInfo> GetArticles(string partitionId,int size = 5)
        {
            var where = PredicateExtension.True<ArticleInfo>();
            where = where.And(u => u.CompanyID == 1);
            where = where.And(u => u.PartitionId == partitionId);
            var list = IMContent.LoadAll(where, 1, size, new OrderByExpression<ArticleInfo, DateTime>(u => u.ReleaseDate, true));
            return list;
        }

        #region 登录

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginInfo">用户输入信息</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login(WebPlatform.Models.LoginVM loginInfo)
        {

            #region 验证登录输入


            if (string.IsNullOrEmpty(loginInfo.LoginName))
            {
                ModelState.AddModelError("LoginName", "请输入用户名");
                BindArticle();
                return View("Index", loginInfo);
            }

            if (string.IsNullOrEmpty(loginInfo.LoginPassword))
            {
                ModelState.AddModelError("LoginPassword", "请输入密码");
                BindArticle();
                return View("Index", loginInfo);
            }

            if (string.IsNullOrEmpty(loginInfo.LoginCode))
            {
                ModelState.AddModelError("LoginCode", "请输入验证码");
                BindArticle();
                return View("Index", loginInfo);
            }

            if (loginInfo.LoginCode != ISHandler.GetSession<string>(WebPlatform.Models.LoginVM.ValidateCodeKey))
            {
                ModelState.AddModelError("LoginCode", "验证码不正确");
                BindArticle();
                return View("Index", loginInfo);
            }


            #endregion

            var user = IMUser.LoginUser(loginInfo.LoginName, loginInfo.LoginPassword);

            if (user != null && user.UserType > 1 )
            {
                if (user.IsCheck == 0) {
                    ModelState.AddModelError("LoginCode", "账户未通过审核");
                    BindArticle();
                    return View("Index", loginInfo);
                }
                #region 保留登录痕迹


                string indate = ISHandler.GetSession<string>(WebPlatform.Models.LoginVM.IndateKey);
                if (string.IsNullOrEmpty(indate) || indate != loginInfo.Indate)
                {
                    if (string.IsNullOrEmpty(loginInfo.Indate))
                    {
                        ISHandler.ClearSession(WebPlatform.Models.LoginVM.IndateKey);
                    }
                    else
                    {
                        var time = ExpirationDate(loginInfo.Indate);
                        ISHandler.CreateSession<string>(WebPlatform.Models.LoginVM.IndateKey, loginInfo.Indate, time);
                        ISHandler.CreateSession<string>(WebPlatform.Models.LoginVM.LoginNameKey, loginInfo.LoginName, time);
                    }
                }


                #endregion


                #region 会话保存


                UserSession uSession = new UserSession();
                uSession.LoginName = user.LoginName;
                uSession.UserID = user.UserID;
                uSession.UserName = user.UserName;
                uSession.UserType = user.UserType;
                uSession.CompanyId = user.CompanyID;
                uSession.Entry = "Front";
                Sessions.User = uSession;

                #endregion


                //清除验证码
                ISHandler.ClearSession(WebPlatform.Models.LoginVM.ValidateCodeKey);

                return RedirectToRoute("Default", new { controller = "Home", action = "Index" });
            }
            else
            {
                ModelState.AddModelError("LoginCode", "用户名或密码不正确");
            }
            BindArticle();
            return View("Index", loginInfo);
        }


        /// <summary>
        /// 生成验证码图片
        /// </summary>
        /// <returns>图片文件</returns>
        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(4);
            ISHandler.CreateSession<string>(WebPlatform.Models.LoginVM.ValidateCodeKey, code, 5);
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }


        /// <summary>
        /// cookie过期时间，分钟
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        int ExpirationDate(string value)
        {
            var now = DateTime.Now;
            switch (value)
            {
                case "oneDay":
                    return 24 * 60;
                case "oneWeek":
                    return 24 * 60 * 7;
                default:
                    return 24 * 60 * (DaysOfMonth(now));
            }
        }


        /// <summary>
        /// 获取该日期中月份天数
        /// </summary>
        /// <param name="dateTime">日期</param>
        /// <returns>月份天数</returns>
        public int DaysOfMonth(DateTime dateTime)
        {
            return (new DateTime(dateTime.Year, dateTime.Month, 1).AddMonths(1) -
                new DateTime(dateTime.Year, dateTime.Month, 1)).Days;
        }


        #endregion



        public ActionResult Partitions(string pid)
        {
            var p = PredicateExtension.True<ProductPartitionInfo>();
            p = p.And(u => u.Level == 0 && u.Enabled == 1 && u.ShowInt == 1);
            if (!string.IsNullOrEmpty(pid))
            {
                p = p.And(u => u.PartitionId.StartsWith(pid));
            }
            var count = IMProduct.LoadCount(p);
            var list = IMProduct.LoadAll(p, 1, count, new OrderByExpression<ProductPartitionInfo, int>(a => a.SortNumber));
            return View(list);
        }

        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private IList<ProductPartitionInfo> GetTypes(string parentId)
        {
            if (string.IsNullOrEmpty(parentId))
            {
                return null;
            }
            var p = PredicateExtension.True<ProductPartitionInfo>();
            p = p.And(u => u.ParentId == parentId && u.Enabled == 1 && u.ShowInt == 1);
            var list = IMProduct.LoadAll(p, 1, 12, new OrderByExpression<ProductPartitionInfo, int>(a => a.SortNumber));
            return list;
        }


        /// <summary>
        /// 分类局部视图
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public ActionResult Types(string parentId)
        {
            ViewBag.TypeList = GetTypes(parentId);
            return PartialView();
        }


        public ActionResult PartialProducts(string partitionId, int page = 1, int pageSize = 2)
        {
            var p = PredicateExtension.True<ProductInfo>();
            p = p.And(u => u.PartitionId == partitionId && u.IsChecked == 1);
            var count = IMProduct.LoadProductCount(p);
            var list = IMProduct.LoadProductAll(p, page, pageSize, new OrderByExpression<ProductInfo, int>(u => u.Id));

            var mapper = ObjectMapperManager.DefaultInstance.GetMapper<ProductInfo, ProductVM>();

            var products = mapper.MapEnum(list);
            PagedList<ProductInfo> plist =
                new PagedList<ProductInfo>(list, page, pageSize, count);

            return PartialView(plist);

        }


        /// <summary>
        /// 获取产品列表
        /// </summary>
        /// <param name="partitionId">分类</param>
        /// <param name="page">当前页</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns></returns>
        public ActionResult Products(string partitionId, int page = 1, int pageSize = 15)
        {
            var partion = IMProduct.GetPartition(partitionId);
            ViewBag.ProPartition = partion;

            var p = PredicateExtension.True<ProductInfo>();
            p = p.And(u => u.PartitionId == partitionId && u.IsChecked == 1);
            var count = IMProduct.LoadProductCount(p);
            var list = IMProduct.LoadProductAll(p, page, pageSize, new OrderByExpression<ProductInfo, DateTime>(u => u.AddDate, true));

            PagedList<ProductInfo> plist =
                new PagedList<ProductInfo>(list, page, pageSize, count);


            return View(plist);
        }
        /// <summary>
        /// 企业注册
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            return View();
        }



        public ActionResult RegSuccess(string lname)
        {
            if (string.IsNullOrEmpty(lname))
            {
                return RedirectToAction("Index");
            }
            ViewBag.LName = "账户名：<strong>" + lname+"</strong>";
            return View();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Register(RegisterVM vm)
        {
            if (ModelState.IsValid)
            {

                var mapper = ObjectMapperManager.DefaultInstance.GetMapper<RegisterVM, UserInfo>();
                var p = mapper.Map(vm);
                p.LoginDateTime = DateTime.Now;
                p.UserType = 2;
                p.LoginIP = Request.UserHostAddress;
                p.Company = new CompanyInfo() { 
                    Name =vm.CompanyName,
                    Email = vm.Email
                    
                };
                p.RegDate = DateTime.Now;
                var b = false;
                try
                {
                    b = IMUser.AddUser(p);
                }
                catch (Exception)
                {
                    //throw;
                }

                return Json(b);
            }
            return Json(false);
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="UserName">新密码</param>
        /// <param name="UserName">确认密码</param>
        /// <returns>false 存在:提示存在 true不存在通过验证  </returns>
        [HttpPost]
        public JsonResult IsSamePassword(string LoginPassword, string ConfirmLoginPassword)
        {
            return Json(LoginPassword == ConfirmLoginPassword);
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="LoginName"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult HasAccount(string LoginName)
        {
           var user = IMUser.GetUser(LoginName);
           return Json(user == null);
        }


        /// <summary>
        /// 文化徽商图片新闻
        /// </summary>
        /// <returns></returns>
        public ActionResult Pictures()
        {
            var articles = GetArticles("HSZZXWPIC", 8);
            ViewBag.Partition = IMArticle.GetPartition("HSZZXWPIC");
            return PartialView(articles);
        }




        /// <summary>
        /// 文章
        /// </summary>
        /// <param name="partitionId">栏目ID</param>
        /// <returns></returns>
        public ActionResult Articles(string partitionId,int size = 5)
        {
            if (string.IsNullOrEmpty(partitionId))
            {
                throw new HttpException(404, "您访问的页面不存在");
            }

           ViewBag.Partition = IMArticle.GetPartition(partitionId);

            var articles = GetArticles(partitionId,size);
            return PartialView(articles);
        }


        /// <summary>
        /// 封面
        /// </summary>
        /// <returns></returns>
        public ActionResult Covers()
        {
            var where = PredicateExtension.True<ArticleInfo>();
            where = where.And(u => u.CompanyID == 1);
            where = where.And(u => u.PartitionId == "HSZZFMPIC");
            var count = IMContent.LoadCount(where);
            var list = IMContent.LoadAll(where, 1, count, new OrderByExpression<ArticleInfo, DateTime>(u => u.ReleaseDate));

            return PartialView(list);
        }


        /// <summary>
        /// 图片链接
        /// </summary>
        /// <returns></returns>
        public ActionResult Links()
        {
            var where = PredicateExtension.True<LinksInfo>();
            where = where.And(u => u.CompanyId == 1 && u.Types == "1");

            var linksCount = IMLinks.LoadCount(where);
            var linksList = IMLinks.LoadAll(where, 1, 6, new OrderByExpression<LinksInfo, int>(u => u.Id));

            return PartialView(linksList);
        }

    }
}
